#!/usr/bin/python
# -*- coding:utf-8 -*-
# @time: 2021/7/8 11:38 上午

import os
import json
import urllib.parse
import zlib
import arrow
import pytz

import requests
import pandas as pd
from datetime import datetime, timedelta
from django.http.request import HttpRequest
from rest_framework.exceptions import ValidationError
from rest_framework.status import is_success
from wass.settings import DJCONSOLE, REQUESTS_VERIFY, TZ_INFO
from utilities.utils import b2m
from utilities.redis import captcha_redis
from utilities.enums import TaskType


CACHE_PREFIX = "djconsole"
CACHED_PATH_DICT = {}


def djconsole_path_cache_wrapper(path, ex=60):
    def wrapper(func):
        def inner_wrapper(*args, **kwargs):
            key = f"{CACHE_PREFIX}:{path}"
            value = captcha_redis.get(key)
            if not value:
                value = func(*args, path=path, **kwargs)
                captcha_redis.set(key, zlib.compress(str(value).encode()), ex=ex)
            else:
                value = eval(zlib.decompress(value))
            CACHED_PATH_DICT[path] = True
            return value
        return inner_wrapper
    return wrapper


def djconsole_delete_path_cache_wrapper(del_path=None):
    def wrapper(func):
        def inner_wrapper(*args, **kwargs):
            res = func(*args, **kwargs)
            if del_path:
                captcha_redis.delete(f"{CACHE_PREFIX}:{del_path}")
                CACHED_PATH_DICT[del_path] = False
            else:
                keys = captcha_redis.keys(f"{CACHE_PREFIX}:*")
                if keys:
                    captcha_redis.delete(*keys)
                for k, v in CACHED_PATH_DICT.items():
                    if v:
                        CACHED_PATH_DICT[k] = False
            return res
        return inner_wrapper
    return wrapper


class Djconsole(object):
    def __init__(self):
        self.base_url = DJCONSOLE.get("base_url")
        self.master_ip = urllib.parse.urlparse(self.base_url).netloc.split(':')[
            0
        ]  # master ip

    def _run_api(
        self,
        request,
        path,
        method,
        data=None,
        file=None,
        json_obj=None,
        base_url=None,
        is_json=False,
        is_not_parse=False,
    ):
        token = request.META.get("HTTP_AUTHORIZATION")
        headers = {}
        if token:
            headers.update({"AUTHORIZATION": token})
        if base_url:  # 集群内指定某台机器
            url = os.path.join(base_url, path)
        else:
            url = os.path.join(self.base_url, path)
        if method == "get":
            response = requests.get(
                url=url, params=data, headers=headers, verify=REQUESTS_VERIFY
            )
        elif method == "post" and file:
            response = requests.post(url=url, data=data, files=file, headers=headers, verify=REQUESTS_VERIFY)
        elif method == "post" and not file:
            if is_json:
                response = requests.post(
                    url=url, json=data, headers=headers, verify=REQUESTS_VERIFY
                )
            else:
                response = requests.post(
                    url=url, data=data, headers=headers, verify=REQUESTS_VERIFY
                )
        elif method == "put":
            response = requests.put(
                url=url,
                data=data,
                json=json_obj,
                headers=headers,
                verify=REQUESTS_VERIFY,
            )
        elif method == "delete":
            response = requests.delete(
                url=url, data=data, headers=headers, verify=REQUESTS_VERIFY
            )
        else:
            raise ValidationError("系统错误")
        if is_not_parse:
            return response
        status_code = response.status_code
        if is_success(status_code):
            return response.json()
        else:
            content = response.text
            try:
                json_data = json.loads(content)
            except json.JSONDecodeError:
                raise ValidationError(content)
            else:
                if isinstance(json_data, dict):
                    error_message = json_data.get('message') or json_data.get('detail')
                    if error_message:
                        raise ValidationError({'message': [error_message]})
                    raise ValidationError(json_data)
                elif isinstance(json_data, list):
                    raise ValidationError({'message': json_data})
                else:
                    raise ValidationError(json_data)

    def format_time(self, str_time, obj=False, hour=False):
        if not str_time:
            return None
        str_time = str_time.split('+')[0]
        if hour:
            m_time = datetime.strptime(str_time, "%Y-%m-%d %H:%M")
        else:
            try:
                m_time = datetime.strptime(str_time, "%Y-%m-%dT%H:%M:%S.%f")
            except ValueError:
                m_time = datetime.strptime(str_time, "%Y-%m-%dT%H:%M:%S")
        target_tz = pytz.timezone(TZ_INFO)
        now = datetime.now(target_tz)
        timezone = str(now)[-6:]
        hours = float(timezone[1:3]) + float(int(timezone[4:]) / 60)
        if timezone[0] == "+":
            m_time += timedelta(hours=hours)
        else:
            m_time -= timedelta(hours=hours)
        if obj:
            return m_time
        return m_time.strftime("%Y-%m-%d %H:%M:%S")

    def get_license_device(self, request):
        license_info_path = "license/info"
        res = {
            "device_id": "未知",
            "product_status": "",
        }
        try:
            device_id = self.get_sys_device(request)
        except Exception:
            pass
        else:
            res.update({"device_id": device_id})

        try:
            data = self._run_api(request, license_info_path, "get")
        except Exception as e:
            if str(e) == "[ErrorDetail(string='License Required', code='invalid')]":
                res.update({"product_status": "not_exists"})
        else:
            res.update({"product_status": "is_expired" if data.get("is_expired") else "有效", "is_trial": data.get("is_trial")})
        return res

    def get_license_info(self, request):
        license_info_path = "license/info"
        data = self._run_api(request, license_info_path, "get")
        task_type_list = [item.value for item in TaskType]
        custom_content = data.get('custom_content')

        modules = data.get('modules', [])
        change_check = TaskType.change_check.value
        if change_check not in modules:
            modules.append(change_check)
        customer = data.get('customer', '')
        res = {
            "company_name": data.get("about", {}).get("company_fullname_cn", ""),
            "product_name": data.get("about", {}).get("product_fullname_cn", ""),
            "is_trial": data.get("is_trial"),
            "product_status": "已失效" if data.get("is_expired") else "有效",
            "is_expired": bool(data.get("is_expired")),
            "device_id": self.get_sys_device(request),
            "product_type": data.get("product_type", ""),
            'modules': modules,
            "expiry_time": arrow.get(data.get("expiry_time", 0)).isoformat()
            if data.get("expiry_time", 0)
            else "未知",
            'is_cluster': data.get('is_cluster', False),
            'custom_content': eval(custom_content) if custom_content else {},
            'customer': "" if customer in ["", "-"] else customer
        }

        # Extra detail
        for k, v in data.items():
            if k.startswith('max') or k in task_type_list:
                res[k] = v
        return res

    @djconsole_path_cache_wrapper(path="license/info", ex=3600)
    def get_license_detail(self, request, path="license/info"):
        res = self._run_api(request, path, "get")
        for item in TaskType:
            if res.get(item.value):
                res[item.value] = eval(res[item.value])
        modules = res.get('modules', [])
        change_check = TaskType.change_check.value
        if change_check not in modules:
            modules.append(change_check)
        res['modules'] = modules
        return res

    @djconsole_delete_path_cache_wrapper()
    def upload_license(self, request, file):
        path = "license/upload"
        data = self._run_api(request, path, "post", {}, file={"file": file})
        res = {
            "company_name": data.get("about", {}).get("company_fullname_cn", ""),
            "product_name": data.get("about", {}).get("product_fullname_cn", ""),
            "is_trial": data.get("is_trial"),
            "product_status": "已失效" if data.get("is_expired") else "有效",
            "device_ids": data.get("device_ids", ["未知"])[0],
            "product_type": data.get("product_type", ""),
        }
        return res

    @djconsole_path_cache_wrapper(path="network")
    def get_network_list(self, request, path):
        data = self._run_api(request, path, "get")
        res = {"ports": data, "primary_dns": "", "secondary_dns": ""}
        for item in data:
            if item["type"] == "work":
                res["primary_dns"] = item.get("primary_dns", "")
                res["secondary_dns"] = item.get("secondary_dns", "")
                break
        return res

    @djconsole_delete_path_cache_wrapper(del_path="network")
    def update_network(self, request, config):
        name = config.get("name")
        path = f"network/{name}/"
        data = self._run_api(request, path, "put", json_obj=config)
        return data

    def ping(self, request, name):
        path = "network/{}/ping/".format(name)
        data = self._run_api(request, path, "post")
        return data

    def get_update_version(self, request):
        path = "update/version"
        data = self._run_api(request, path, "get")
        updated_time = data.get("updated_at")
        data_updated_at = data.get("data_updated_at")
        if updated_time:
            data["updated_at"] = self.format_time(updated_time)
        else:
            data["updated_at"] = "没有做过系统更新升级"
        if data_updated_at:
            data["data_updated_at"] = self.format_time(data_updated_at)
        else:
            data["data_updated_at"] = "没有做过数据更新升级"
        return data

    def get_update_info(self, request, tag=None):
        data = self.get_update_version(request)
        license = self.get_license_device(request)
        data["license_status"] = license.get("product_status")
        return data

    def update_update_config(self, request, config):
        path = "update/config"
        data = self._run_api(request, path, "post", config)
        return data

    def upload_update_file(self, request, config):
        path = "update/upload"
        file = config.pop("file")
        data = self._run_api(request, path, "post", config, file={"file": file})
        return data

    def upgrade_update(self, request, tag):
        path = "update/upgrade"
        data = self._run_api(request, path, "post", {"tag": tag})
        return data

    def upload_and_upgrade(self, request, config):
        path = "update/upload-upgrade"
        file = config.pop("file")
        data = self._run_api(request, path, "post", config, file={"file": file})
        return data

    def upload_and_upgrade_clusters(self, request, config):
        """主节点升级了 从节点跟着自动升级"""
        path = "update/upload-upgrade"
        cluster_ips = self.get_cluster_ip(request)
        for cluster_ip in cluster_ips:
            base_url = self.get_cluster_url(cluster_ip['node_ip'])
            try:
                self._run_api(
                    request, path, "post", config, file=True, base_url=base_url
                )
            except Exception as e:
                print(e)

    def get_device_data(self, request):
        """系统状态数据"""
        path = "sysstat-device"
        params = {"delta_hours": 24}
        if request.query_params.get('device_id'):
            params['device_id'] = request.query_params.get('device_id')
        data = self._run_api(request, path, "get", data=params) or []
        for _d in data:
            _d["created_at"] = self.format_time(_d["created_at"], obj=True)
        data.sort(key=lambda _: _["created_at"])
        return data

    def get_device_status(self, request):
        """单机系统状态数据"""
        path = "sysstat-device"
        params = {"delta_hours": 24}
        data = self._run_api(request, path, "get", data=params) or []
        now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        if not data:
            result = {
                "boot_time_str": f"0天0小时0分钟",
                "status": "online",
                "last_update_time": now_time,
                "node_ip": "127.0.0.1",
            }
            return result
        for _d in data:
            _d["created_at"] = self.format_time(_d["created_at"], obj=True)
        data.sort(key=lambda _: _["created_at"])
        tail_data = data[-1]
        day, hour, minute = self.get_uptime(request)
        result = {
            "boot_time_str": f"{day}天{hour}小时{minute}分钟",
            "status": "online",
            "last_update_time": now_time,
            "node_ip": tail_data["node_ip"],
        }
        return result

    def get_device_system_status(self, request):
        """获取系统负载状态"""
        data = self.get_device_data(request)
        if not data:
            empty_list = [0] * 10
            result = {
                "cpu_percent": 0,
                "cpu_percent_list": empty_list,
                "mem_percent": 0,
                "mem_percent_list": [],
                "disk_sys_percent": 0,
                "disk_sys_percent_list": empty_list,
                "disk_data_percent": 0,
                "disk_data_percent_list": empty_list,
                "created_at": [],
            }
            return result

        tail_data = data[-1]
        result = {
            "cpu_percent": tail_data["cpu_percent"],
            "cpu_percent_list": [],
            "mem_percent": tail_data["mem_percent"],
            "mem_percent_list": [],
            "disk_sys_percent": tail_data["disk_sys_percent"],
            "disk_sys_percent_list": [],
            "disk_data_percent": tail_data["disk_data_percent"],
            "disk_data_percent_list": [],
            "disk_business_percent": tail_data["disk_business_percent"],
            "disk_business_percent_list": [],
            "created_at": [],
        }
        for item in data:
            result["cpu_percent_list"].append(item["cpu_percent"])
            result["mem_percent_list"].append(item["mem_percent"])
            result["disk_sys_percent_list"].append(item["disk_sys_percent"])
            result["disk_data_percent_list"].append(item["disk_data_percent"])
            result["disk_business_percent_list"].append(item['disk_business_percent'])
            result["created_at"].append(item["created_at"])
        return result

    def get_device_business_status(self, request):
        """业务负载数据"""
        data = self.get_device_data(request)
        if not data:
            empty_list = [0] * 10
            result = {
                "net_bytes_recv": 0,
                "net_bytes_recv_list": empty_list,
                "net_bytes_sent": 0,
                "net_bytes_sent_list": empty_list,
                "net_packets_recv": 0,
                "net_packets_recv_list": empty_list,
                "net_packets_sent": 0,
                "net_packets_sent_list": empty_list,
                "created_at": [],
            }
            return result
        tail_data = data[-1]
        result = {
            "net_bytes_recv": tail_data["net_bytes_recv"],
            "net_bytes_recv_list": [],
            "net_bytes_sent": tail_data["net_bytes_sent"],
            "net_bytes_sent_list": [],
            "net_packets_recv": tail_data["net_packets_recv"],
            "net_packets_recv_list": [],
            "net_packets_sent": tail_data["net_packets_sent"],
            "net_packets_sent_list": [],
            "created_at": [],
        }
        for item in data:
            result["net_bytes_recv_list"].append(item["net_bytes_recv"])
            result["net_bytes_sent_list"].append(item["net_bytes_sent"])
            result["net_packets_recv_list"].append(item["net_packets_recv"])
            result["net_packets_sent_list"].append(item["net_packets_sent"])
            result["created_at"].append(item["created_at"])
        return result

    def get_dvol_usage(self, request, device_id):
        """数据磁盘 占用率"""
        path = "sysstat-device"
        params = {"delta_hours": 9, "device_id": device_id}
        data = self._run_api(request, path, "get", data=params) or []
        for _d in data:
            _d["created_at"] = self.format_time(_d["created_at"], obj=True)
        data.sort(key=lambda _: _["created_at"])
        tail_data = data[-1] if data else {}
        return tail_data

    def get_ntp_info(self, request):
        path = "systool/ntp/info"
        api_url = self.get_cluster_url(request.query_params.get('node_ip'))
        data = self._run_api(request, path, "get", base_url=api_url)
        return data

    def set_ntp_conf(self, request, post_data):
        path = "systool/ntp/set_ntp_ip"
        api_url = self.get_cluster_url(request.data.get('node_ip'))
        data = self._run_api(request, path, "post", data=post_data, base_url=api_url)
        return data

    def set_ntp_time(self, request, post_data):
        path = "systool/ntp/set_ntp_time"
        api_url = self.get_cluster_url(request.data.get('node_ip'))
        data = self._run_api(request, path, "post", data=post_data, base_url=api_url)
        return data

    def set_loc_time(self, request, post_data):
        path = "systool/ntp/set_loc_time"
        api_url = self.get_cluster_url(request.data.get('node_ip'))
        data = self._run_api(request, path, "post", data=post_data, base_url=api_url)
        return data

    def get_uptime(self, request):
        """获取开机时长"""
        path = "device/boottime"
        api_url = self.get_cluster_url(request.query_params.get('node_ip'))
        data = self._run_api(request, path, "get", base_url=api_url)
        up_time_seconds = data.get("data").get("up_time_seconds")
        day = int(up_time_seconds / (24 * 60 * 60))
        hour = int((up_time_seconds % (24 * 60 * 60)) / (60 * 60))
        minute = int(up_time_seconds % (60 * 60) / 60)
        return day, hour, minute

    def get_device_version(self, request):
        path = "sysstat-device"
        version = self._run_api(request, path, "get")
        if version:
            version = version[0].get("version")
        else:
            version = "未知"
        return version

    def get_support(self, request):
        path = "support-v2/status"
        res = {"enabled": False, "id": ""}
        data = self._run_api(request, path, "get")
        if not isinstance(data, list):
            return res
        for d in data:
            if int(d.get("status_code", 1)) == 1:
                return res
            res["enabled"] = True
            name = d.get("name", "")
            if not name.startswith("web"):
                res["id"] = name
        return res

    def get_route(self, request):
        path = 'routes/routes_info/'
        data = self._run_api(request, path, "get")
        return data

    def add_route(self, request, data):
        path = "routes/add_route/"
        data = self._run_api(request, path, "post", data)
        return data

    def delete_route(self, request, data):
        path = "routes/del_routes/"
        data = self._run_api(request, path, "post", data, is_json=True)
        return data

    def start_support(self, request, config):
        path = "support-v2/start"
        data = self._run_api(request, path, "post", config)
        return data

    def close_support(self, request):
        path = "support-v2/stop"
        data = self._run_api(request, path, "post")
        return data

    def shutdown(self, request):
        path = "device/poweroff"
        try:
            data = self._run_api(request, path, "post")
        except requests.exceptions.ConnectionError:  # 关机 连接丢失 无返回
            data = {'msg': '正在关机...'}
        return data

    def reboot(self, request):
        path = "device/reboot"
        data = self._run_api(request, path, "post")
        return data

    def network_enable(self, request, name):
        path = "network/{}/enable/".format(name)
        data = self._run_api(request, path, "post")
        return data

    def network_disable(self, request, name):
        path = "network/{}/disable/".format(name)
        data = self._run_api(request, path, "post")
        return data

    def get_sys_device(self, request):
        path = 'license/device'
        return self._run_api(request, path, "get")

    def get_sysstate_node(self, request):
        path = "sysstat-node/"
        data = self._run_api(request, path, "get")
        return data

    def get_network_name(self, request):
        path = "sysstat-network/name/"
        data = self._run_api(request, path, "get")
        return data

    def get_network_statistics(self, request):
        path = "sysstat-network/io-stat/"
        data = self._run_api(request, path, "get")
        result = []
        for item in data:
            _ = {
                "rx": {
                    "current": b2m(item.get("net_bytes_recv_cur", 0)),
                    "avg": b2m(item.get("net_bytes_recv_avg", 0)),
                    "max": b2m(item.get("net_bytes_recv_max", 0)),
                },
                "tx": {
                    "current": b2m(item.get("net_bytes_sent_cur", 0)),
                    "avg": b2m(item.get("net_bytes_sent_avg", 0)),
                    "max": b2m(item.get("net_bytes_sent_max", 0)),
                },
                "type": item.get("_id"),
            }
            result.append(_)
        return result

    def get_network_detail(self, request, time, networks, kind):
        path = "sysstat-network/io/"
        from_time = (
            datetime.now() - timedelta(days=6)
            if time == "week"
            else datetime.now() - timedelta(hours=23)
        )
        if time == "week":
            group_by = "day"
            from_time = from_time.strftime('%Y-%m-%d 00:00:00')
            fmt = "%Y-%m-%d"
        else:
            group_by = "hour"
            from_time = from_time.strftime('%Y-%m-%d %H:00:00')
            fmt = "%Y-%m-%d %H:%M"
        params = {
            "network_names": networks,
            "from_time": from_time,
            "group_by": group_by,
        }
        dj_data = self._run_api(request, path, "get", data=params) or dict()
        data = dj_data.get("data")
        last_time = dj_data.get("last_time")
        if not data:
            if time == "day":
                category = [
                    (datetime.now() - timedelta(hours=i)).strftime('%Y-%m-%d %H:00' '')
                    for i in range(23, -1, -1)
                ]
            else:
                category = [
                    (datetime.now() - timedelta(days=i)).strftime('%Y-%m-%d')
                    for i in range(6, -1, -1)
                ]
            return {
                "category": category,
                "rx": [],
                "tx": [],
                "last_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            }
        kind = "bytes" if kind == "bps" else "packets"
        rx = []
        tx = []
        eth_names = networks.split(",")
        df = pd.DataFrame(data=data)
        category = set(df.get("time"))
        category = [datetime.strptime(s, fmt) for s in category]
        category.sort()
        category = [s.strftime(fmt) for s in category]
        for cgy in category:
            _rx = {
                n: df.query(f"name == '{n}' and time == '{cgy}'")
                .get(f"net_{kind}_recv")
                .sum()
                for n in eth_names
            }
            _tx = {
                n: df.query(f"name == '{n}' and time == '{cgy}'")
                .get(f"net_{kind}_sent")
                .sum()
                for n in eth_names
            }
            rx.append(_rx)
            tx.append(_tx)
        result = {"category": category, "rx": rx, "tx": tx, "last_time": last_time}
        return result

    def update_mode(self, mode, detail, ipfw):
        try:
            res = update_mode(mode, detail, ipfw)  # noqa: F821
        except Exception as e:
            if type(e) == ValidationError:
                e = e.args
            raise ValidationError(e)
        return res

    def get_transparent_config(self):
        return get_transparent_config()  # noqa: F821

    def get_snmp_info(self, request):
        path = "snmp/info"
        data = self._run_api(request, path, "get")
        return data

    def post_snmp_service(self, request, post_data):
        path = "snmp/server"
        data = self._run_api(request, path, "post", data=post_data)
        return data

    def set_snmp_name(self, request, post_data):
        path = "snmp/set_name"
        data = self._run_api(request, path, "post", data=post_data)
        return data

    def add_snmp_user(self, request, post_data):
        path = "snmp/add_user"
        data = self._run_api(request, path, "post", data=post_data)
        return data

    def del_snmp_user(self, request, post_data):
        path = "snmp/delete_user"
        data = self._run_api(request, path, "post", data=post_data)
        return data

    def get_network_status(self, request):
        path = "sysstat-network/stats/"
        data = self._run_api(request, path, "get")
        return data

    def get_cpu_mem_status(self, request):
        path = "device/status"
        data = self._run_api(request, path, "get")
        return data

    def get_cluster_ip(self, request):
        devices = self.get_sys_device(request)
        cluster_ip = [
            node
            for node in devices
            if node['node_ip'] not in ('127.0.0.1', self.master_ip)
        ]
        return cluster_ip

    def get_cluster_url(self, device_ip=None):
        """集群内有多台机器， 指定的ip"""
        if not device_ip:
            return None
        if device_ip == '127.0.0.1':
            return None
        return self.base_url.replace(self.master_ip, device_ip)

    def get_cluster_list(self, request, detail=None):
        path = "cluster/list"
        if detail:
            params = {"detail": detail}
            data = self._run_api(request, path, "get", data=params)
        else:
            data = self._run_api(request, path, "get")
        if data.get('data', []):
            for index, one_data in enumerate(data['data']):
                data['data'][index]["created_at"] = self.format_time(one_data["created_at"], obj=True)
                data['data'][index]["updated_at"] = self.format_time(one_data["updated_at"], obj=True)
        if data.get('role_data', {}):
            data['role_data']['mgmt'] = "管理节点"
        return data

    def is_cluster(self, request):
        if self.get_license_detail(request).get('is_cluster'):
            return True
        return False

    def update_log(self, request):
        path = "update/log"
        data = self._run_api(request, path, "get", data=request.query_params)
        if data['results']:
            for index, one_data in enumerate(data['results']):
                data['results'][index]["started_at"] = self.format_time(one_data["started_at"], obj=True)
                data['results'][index]["ended_at"] = self.format_time(one_data["ended_at"], obj=True)
        return data

    def add_node(self, request, post_data):
        path = "cluster/add"
        data = self._run_api(request, path, "post", data=post_data)
        return data

    def change_node(self, request, post_data, kind):
        path = "cluster/{}".format(kind)
        data = self._run_api(request, path, "post", data=post_data)
        return data

    def bk_backup(self, request):
        path = "backup-recovery/backup"
        response = self._run_api(request, path, "post", is_not_parse=True)
        return response.json()

    def bk_recovery(self, request, bk_id):
        path = "backup-recovery/recovery"
        response = self._run_api(request, path, "post", data={"id": bk_id}, is_json=True, is_not_parse=True)
        return response.json()

    def bk_progress(self, request, kind):
        path = "backup-recovery/progress"
        response = self._run_api(request, path, "get", data={"type": kind}, is_not_parse=True)
        data = response.json()
        if not is_success(response.status_code):
            data.update({
                "type": kind,
                "status": 4   # 没有进行备份恢复
            })
        return data

    def bk_query_record(self, request, kind):
        path = f"backup-recovery/{kind}-info"
        data = self._run_api(request, path, "get", data=request.query_params)
        if data['results']:
            for index, one_data in enumerate(data['results']):
                data['results'][index]["started_at"] = self.format_time(one_data["started_at"], obj=True)
                data['results'][index]["ended_at"] = self.format_time(one_data["ended_at"], obj=True)
        return data

    def bk_delete_record(self, request, ids):
        path = "backup-recovery/delete"
        data = self._run_api(request, path, "post", data={"ids": ids}, is_json=True)
        return data

    def bk_download_file(self, request, bk_id):
        path = "backup-recovery/download"
        data = self._run_api(request, path, "get", data={"id": bk_id}, is_not_parse=True)
        return data

    def bk_upload_file(self, request, conf):
        path = "backup-recovery/upload"
        data = self._run_api(request, path, "post", data=conf, is_json=True)
        return data

    def _check_is_bk(self, kind):
        try:
            data = self.bk_progress(HttpRequest(), kind)
        except ValidationError:
            return False
        else:
            status = int(data.get("status", 2))
            if status == 1:
                return True

    def check_is_bk(self):
        for kind in ["backup", "recovery"]:
            flag = self._check_is_bk(kind)
            if flag:
                return flag
        return flag

    def get_ssh_status(self, request):
        path = "ssh/status"
        data = self._run_api(request, path, "get")
        return data

    def change_ssh_status(self, request, action):
        path = "ssh/server"
        data = self._run_api(request, path, "post", data={"action": action}, is_json=True)
        return data


djconsole = Djconsole()
